//
//  CourseDetialTableViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/1.
//

#import "CourseDetialTableViewController.h"
#import "MyCollectionListCell.h"
#import "CourseWordsListManager.h"
#import <AVFoundation/AVFoundation.h>
#import "WordDetialViewController.h"
#import "JPNavigationController.h"

@interface CourseDetialTableViewController ()<
///AVSpeechSynthesizerDelegate,
UITableViewDelegate,
UITableViewDataSource,
JPAPIManagerCallBackDelegate
>

@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)CourseWordsListManager *courseWordsManager;
@property(nonatomic,strong)MyCollectionListCell *currentCell;
@property(nonatomic,assign)NSInteger playIndex;
//@property(nonatomic,strong)AVSpeechSynthesizer *synthesizer;

@end

@implementation CourseDetialTableViewController

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(CourseWordsListManager *)courseWordsManager{
    if(!_courseWordsManager){
        _courseWordsManager = [[CourseWordsListManager alloc]init];
        _courseWordsManager.delegate = self;
    }
    return _courseWordsManager;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.playIndex = -1;

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,self.view.width,self.view.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 90;
    [self.tableView registerClass:NSClassFromString(@"MyCollectionListCell") forCellReuseIdentifier:@"MyCollectionListCell"];
    
    __weak typeof(self)self_weak_ = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self_weak_.dataArr removeAllObjects];
        [self_weak_ loadData];
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(wordDetialCollectRefresh:) name:@"WordDetialCollectRefresh" object:nil];
    
}

- (void)refreshWidth {
    
    // 更新 tableView 尺寸
    self.tableView.width = self.currentAvailableWidth;
    self.tableView.height = self.currentAvailableHeight;

    // 重新加载数据
    [self.tableView reloadData];
}


#pragma mark - 单词详情改变了收藏状态
-(void)wordDetialCollectRefresh:(NSNotification*)notifi{
    if(notifi.object){
        WordListModel *model = notifi.object;
        for(NSInteger i = 0;i < self.dataArr.count;i++){
            WordListModel *model2 = self.dataArr[i];
            if([model.wordId isEqualToString:model2.wordId]){
                model2.isCollect = model.isCollect;
                [self.dataArr replaceObjectAtIndex:i withObject:model2];
                break;
            }
        }
        [self.tableView reloadData];
    }
}


#pragma mark - 获取数据
-(void)loadData{
    self.playIndex = -1;
    //停止正在播放的
    [self stopSpeaking];
    self.courseWordsManager.type = [NSString stringWithFormat:@"%ld",_sel_index+1];
    self.courseWordsManager.courseId = self.courseId;
    [self.courseWordsManager loadData];
}

-(void)setSel_index:(NSInteger)sel_index{
    _sel_index = sel_index;
    self.playIndex = -1;
    //停止正在播放的
    [self stopSpeaking];
    if(self.dataArr.count == 0){
        self.courseWordsManager.type = [NSString stringWithFormat:@"%ld",sel_index+1];
        self.courseWordsManager.courseId = self.courseId;
        [self.courseWordsManager loadData];
    }
}

-(void)setIsSel:(BOOL)isSel{
    _isSel = isSel;
    [self.tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCollectionListCell"];
    if(indexPath.row < self.dataArr.count){
        cell.isSel = self.isSel;
        WordListModel *model = self.dataArr[indexPath.row];
        cell.wordModel = model;
        __weak typeof(self)self_weak_ = self;
        __weak typeof(cell)cell_weak_ = cell;
        [cell setPlayBlock:^{
            //停止正在播放的
            [self_weak_ stopSpeaking];
            self_weak_.currentCell = cell_weak_;
            if(indexPath.row == self_weak_.playIndex){
                //暂停
                self_weak_.playIndex = -1;
            }else{
                //播放
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self_weak_.playIndex = indexPath.row;
                    if(model.audio&&![model.audio isEqualToString:@""]){
                        [self_weak_ playAudio:model.audio];
                    }else{
                        if((model.pronunciation)&&(![model.pronunciation isEqualToString:@""])){
                            if((model.writing)&&(model.isReadWriting)&&([model.isReadWriting isEqualToString:@"1"]||model.isReadWriting.integerValue == 1)){
                                [self_weak_ speakJapaneseText:model.writing];
                            }else{
                                [self_weak_ speakJapaneseText:model.pronunciation];
                            }
                        }else{
                            if((model.writing)&&(![model.writing isEqualToString:@""])){
                                [self_weak_ speakJapaneseText:model.writing];
                            }
                        }
                    }
                });
            }
        }];
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < self.dataArr.count){
        [self stopSpeaking];
        WordListModel *model = self.dataArr[indexPath.row];
        WordDetialViewController *vc = [[WordDetialViewController alloc]init];
        vc.wordModel = model;
        JPNavigationController *nav = [[JPNavigationController alloc]initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - 播放读取文本
- (void)speakJapaneseText:(NSString *)text{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        [self.currentCell startVoiceAnimation];
    }
//    if(!self.synthesizer){
//        self.synthesizer = [[AVSpeechSynthesizer alloc] init];
//        self.synthesizer.delegate = self;
//    }
//    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
//    utterance.rate = 0.53; // 语速，范围0.0~1.0
//    utterance.pitchMultiplier = 1.1; // 音高，范围0.5~2.0
//    utterance.volume = 1.0; // 音量，范围0~1
//    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"ja-JP"];
//    utterance.voice = voice;
//    [self.synthesizer speakUtterance:utterance];

    
    if (self.delegate && [self.delegate respondsToSelector:@selector(speakText: andText:)]){
        [self.delegate speakText:self andText:text];
    }
    
}


#pragma mark - 停止当前正在读的文本
- (void)stopSpeaking{
//    if (self.synthesizer&&self.synthesizer.isSpeaking) {
//        [self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
//        if(self.currentCell){
//            [self.currentCell stopVoiceAnimation];
//        }
//    }
    
    if(self.currentCell){
        [self.currentCell stopVoiceAnimation];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(stopSpeak:)]){
        [self.delegate stopSpeak:self];
    }
}

#pragma mark - 播放音频读音
- (void)playAudio:(NSString*)audio{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        [self.currentCell startVoiceAnimation];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(playAudio:andAudio:)]){
        [self.delegate playAudio:self andAudio:audio];
    }
    
}

//#pragma mark - AVSpeechSynthesizer deletage
//- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
//    // 当前文本已经读完
//    if(self.currentCell){
//        [self.currentCell stopVoiceAnimation];
//    }
//    self.playIndex =  -1;
//}

#pragma mark - 停止播放动画
-(void)stopPlayAnimation{
    if(self.currentCell){
        [self.currentCell stopVoiceAnimation];
        self.playIndex = -1;
    }
}

#pragma mark - 设置静音模式下也能播放音频
-(void)listentTypeSet{
    // 获取当前的音频会话类别
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    // 检查当前类别是否已经是 AVAudioSessionCategoryPlayback
    if (![audioSession.category isEqualToString:AVAudioSessionCategoryPlayback]) {
        NSError *setCategoryError = nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
        
        if (setCategoryError) {
            NSLog(@"Error setting category: %@", [setCategoryError localizedDescription]);
        }
    }
    
    // 检查音频会话是否已经处于激活状态
    if (!audioSession.isOtherAudioPlaying) {
        NSError *activationError = nil;
        [audioSession setActive:YES error:&activationError];
        
        if (activationError) {
            NSLog(@"Error activating session: %@", [activationError localizedDescription]);
        }
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.courseWordsManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [WordListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    [self.tableView.mj_header endRefreshing];
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
